package com.nisco.nio.socketchannel;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;

/**
 * serverSocketChannel负责监听socket，并创建socketChannel，本身并不传输数据
 * 可以在非阻塞下运行
 * accept：--> socketChannel 可在非阻塞模式下运行
 *
 **/
public class ServerSocketChannelTest {
    public static void main(String[] args)
        throws Exception {
        // 端口号
        int port = 8000;

        // buffer
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        buffer.put("a".getBytes(StandardCharsets.UTF_16BE));
        buffer.flip();
        while (buffer.hasRemaining()) {
            System.out.println(buffer.get());
        }

//        buffer.put("<a href='http://www.baidu.com'>welcome you!</a>".getBytes());

        // ServerSocketChannel
        ServerSocketChannel ssc = ServerSocketChannel.open();

        // binding
        ssc.socket().bind(new InetSocketAddress(port));

        // 设置非阻塞模式
        ssc.configureBlocking(false);

        // 监听
        while (true) {
            SocketChannel socketChannel = ssc.accept();  // 非阻塞模式
            if (socketChannel == null) {
                System.out.println("等待连接...");
                Thread.sleep(2000);
                continue;
            }
            System.out.println("连接来自" + socketChannel.socket().getRemoteSocketAddress());

            buffer.flip();
            socketChannel.write(buffer);

            socketChannel.close();
        }

    }
}
